package com.example.springboottest.p6spy;

import com.p6spy.engine.common.PreparedStatementInformation;
import com.p6spy.engine.common.StatementInformation;
import com.p6spy.engine.event.JdbcEventListener;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

/**
 * @author tangsw   2018/4/14.
 */
public class SchemaRecordEventListener extends JdbcEventListener {
    static final ThreadLocal<String> currentSchema = new ThreadLocal<>();

    private void recordSchema(StatementInformation statementInformation) {
        String schema = "??";
        try {
            schema = statementInformation.getConnectionInformation().getConnection().getSchema();
        } catch (SQLException ignored) {
        }
        currentSchema.set(schema);
    }

    @Override
    public void onBeforeExecute(PreparedStatementInformation statementInformation) {
        recordSchema(statementInformation);
    }

    @Override
    public void onBeforeExecuteBatch(StatementInformation statementInformation) {
        recordSchema(statementInformation);
    }

    @Override
    public void onBeforeExecuteUpdate(PreparedStatementInformation statementInformation) {
        recordSchema(statementInformation);
    }

    @Override
    public void onBeforeExecuteUpdate(StatementInformation statementInformation, String sql) {
        recordSchema(statementInformation);
    }

    @Override
    public void onBeforeExecuteQuery(PreparedStatementInformation statementInformation) {
        recordSchema(statementInformation);
    }

    @Override
    public void onBeforeExecuteQuery(StatementInformation statementInformation, String sql) {
        recordSchema(statementInformation);
    }
}
